<template>
  <!-- 展览众筹添加组件 -->
  <div class="upload-form">
    <el-form :model="form" :rules="rules" ref="form">
      <el-form-item label="展览标题" :label-width="formLabelWidth" prop="title">
        <el-input v-model="form.title" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="展览简介" :label-width="formLabelWidth" prop="intro">
        <el-input type="textarea" v-model="form.intro" rows="4"></el-input>
      </el-form-item>
      <el-form-item label="展览主图" :label-width="formLabelWidth" prop="mainPic">
        <el-upload id="mainPic" action="" list-type="picture-card" ref="mainPic" :auto-upload="false" :multiple="false" :limit="1"
          accept="image/*" :class="{'hide':mainPicUrl.length !== 0}" class="input-item" :on-change="mainPicChange" :on-remove="mainPicRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="* 展览图集" :label-width="formLabelWidth" prop="pics">
        <el-upload id="pics" action="" list-type="picture-card" ref="pics" :auto-upload="false" :multiple="true" :limit="10" accept="image/*"
          :class="{'hide':picsUrl.length >= 4}" :on-change="picsChange" :on-remove="picsRemove" :on-exceed="exceedLimit" v-model="form.pics">
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="* 展览附件" :label-width="formLabelWidth" prop="planFile">
        <el-upload id="planFile" action="" :auto-upload="false" ref="planFile" :multiple="false" :limit="1" :file-list="planFiles"
          list-type="text" accept="application/msword,application/pdf,application/excel,application/x-msexcel,application/x-excel,application/x-compressed,application/x-zip-compressed,application/zip,multipart/x-zip"
          :class="{'hide':planFileUrl.length !== 0}" class="input-item" :on-change="planFileChange" :on-remove="planFileRemove"
          v-model="form.planFile">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <div slot="tip" class="el-upload__tip">支持pdf、word、excel、zip，且不超过10mb</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer xui-text-center">
      <el-button type="primary" v-loading="loading" :disabled="disable" @click="validateAndSubmit">确 定</el-button>
    </div>
  </div>
</template>
<script>
  import {
    childrenEle
  } from "@/utils";
  import {
    getToken
  } from "@/utils/auth.js";
  import {
    rootsUrl
  } from "@/utils";
  export default {
    props: ["id"],
    data() {
      return {
        files: [],
        formLabelWidth: "120px",
        form: {
          title: "",
          intro: "",
          mainPic: null,
          pics: [],
          planFile: null
        },
        pics: [],
        planFile: null,
        mainPicUrl: "",
        picsUrl: [],
        planFileUrl: "",
        planFiles: [],
        rules: {
          title: [{
            required: true,
            message: "请输入作品标题",
            trigger: "blur"
          }],
          intro: [{
            required: true,
            message: "请输入作品简介",
            trigger: "blur"
          }],
          mainPic: [{
            required: true,
            message: "请上传主图",
            trigger: "change"
          }],
        },
        loading: false,
        disable: false
      };
    },
    computed: {
      userId() {
        return this.$store.getters.userId;
      },
      userName() {
        return this.$store.getters.userName;
      },
      uploadUrl() {
        return `${rootsUrl[0]}/museum/design/saveDesign.shtml`;
      }
    },
    methods: {
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      mainPicChange(file) {
        if (!file) {
          return false;
        }
        if (this.picCondition(file)) {
          this.mainPicUrl = file.url;
          this.form.mainPic = file.url;
        } else {
          this.$refs.mainPic.clearFiles();
        }
      },
      mainPicRemove(file) {
        if (!file) {
          return false;
        }
        if (this.mainPicUrl == file.url) {
          console.log(file)
          this.mainPicUrl = "";
          this.form.mainPic = "";
          this.$refs.mainPic.clearFiles();
        }
      },
      picsChange(file, fileList) {
        this.picsUrl.push(file.url);
        this.files.push(file.raw);
      },
      picsRemove(file) {
        if (!file) {
          return false;
        }
        let index = this.picsUrl.indexOf(file.url);
        if (index > -1) {
          this.picsUrl.splice(index, 1);
        }
        this.files.splice(this.files.indexOf(file.raw), 1);
      },
      planFileChange(file) {
        if (!file) {
          return false;
        }
        if (this.planFileCondition(file)) {
          this.planFileUrl = file.url;
          this.form.planFile = file.raw;
        } else {
          this.$refs.planFile.clearFiles();
        }
      },
      planFileRemove(file) {
        if (!file) {
          return false;
        }
        if (this.planFileUrl == file.url) {
          this.planFileUrl = "";
          this.form.planFile = null;
          this.$refs.planFile.clearFiles();
        }
      },
      picCondition(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error("上传文件大小不能超过 2MB!");
        }
        return isLt2M;
      },
      planFileCondition(file) {
        const isLt10M = file.size / 1024 / 1024 < 10;
        if (!isLt10M) {
          this.$message.error("上传文件大小不能超过 10MB!");
        }
        return isLt10M;
      },
      submitArt() {
        // loading状态
        this.loading = true;
        this.disable = true;
        // 新建formdata对象
        let data = new FormData();
        // 将数据手动添加到formData对象中
        data.append("aid", this.id);
        data.append("uid", this.userId);
        data.append("uname", this.userName);
        data.append("title", this.form.title);
        data.append("content", this.form.intro);
        let token = getToken();
        data.append("token", token);
        let mainPic = document.getElementById("mainPic").children[1].children[1]
          .files;
        data.append("picture", mainPic[0]); //通过append向form对象添加数据
        let planFile = this.form.planFile;
        data.append("planFile", planFile);
        let pics = this.files;
        for (let i = 0; i < pics.length; i++) {
          data.append("pictures", pics[i]);
        }
        // 设置请求头格式
        let config = {
          headers: {
            "Content-Type": "multipart/form-data"
          }
        };
        // 通过post方式提交数据。
        this.$axios
          .post(this.uploadUrl, data, config)
          .then(res => {
            this.loading = false;
            this.disable = false;
            if (res.data.flag != 1) {
              this.$message({
                showClose: true,
                type: "error",
                message: res.data.msg
              });
              return false;
            }
            this.$message({
              showClose: true,
              type: "success",
              message: res.data.msg + "审批通过后显示出来。"
            });
            this.$emit("done");
            this.$refs.form.resetFields();
            this.$refs.mainPic.clearFiles();
            this.$refs.pics.clearFiles();
            this.$refs.planFile.clearFiles();
            this.mainPicUrl = "";
            this.picsUrl = [];
            this.form;
          })
          .catch(err => {
            this.loading = false;
            this.disable = false;
          });
      },
      validateAndSubmit() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.picsUrl < 1) {
              this.$message({
                showClose: true,
                type: "error",
                message: "请选择图集的图片后再上传。"
              });
              return false;
            }
            if (!this.planFileUrl) {
              this.$message({
                showClose: true,
                type: "error",
                message: "请选择展览附件后再上传。"
              });
              return false;
            }
            this.submitArt();
          } else {
            this.$message({
              showClose: true,
              type: "error",
              message: "请填写相关信息后再上传。"
            });
          }
        });
      },
      exceedLimit() {
        this.$message({
          type: "warning",
          message: "最多上传4张创意图集"
        });
      }
    },
    mounted() {
      this.mainPicUrl = "";
      this.form.pics = "";
      this.$refs.pics.clearFiles();
    }
  };

</script>

<style lang="less">
  .upload-form .input-item.hide {
    // height: 96px;
    .el-upload--picture-card {
      display: none !important;
    }
    position: relative;
  }

  .upload-form #pics.hide {
    .el-upload--picture-card {
      display: none !important;
    }
  }

  .upload-form {
    .el-upload__tip {
      line-height: 20px;
      color: #f75d5d;
      margin-top: 0;
    }
  }

  .el-button--primary {
    color: #fff;
    background-color: #dbad23;
    border-color: #dbad23;
  }

</style>
